//
//  HOTabViewController.m

//  WeiDu_1_0
//

//  Created by foguo-mac-1 on 01/07/16.

//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.

//



#import "HOTabViewController.h"
#import "HOBaseViewController.h"
#import "HOMyViewController.h"
#import "HOAppDataModule.h"
#import "HOUIMgr.h"
#import "HONavigationController.h"
#import "HOUtils.h"
#import "HOConstants.h"
#import "HOMessageController.h"
#import "HOFillInfoViewController.h"
#import "HOLoginViewController.h"
#import "HOQuickReportViewController.h"
#import "HODefine.h"
#import "HOReportListViewController.h"
#import "HOReportViewController.h"
#import "HOReportDetailViewController.h"
#import "HOMaintainHistoryViewController.h"
#import "HOMyReportViewController.h"
#import "HOStaticDataMgr.h"
#import "HOReportViewController.h"
#import "HOAnalyzeViewController.h"
#import "Logger.h"
#import "HOGlobalData.h"
#import "HOAppController.h"

@interface HOTabViewController()
{
	UIButton	*translatorImgViewBtn;
	UIButton		*translatorBtn;
	UIView		*bubbleView;
	UIButton 	 *bubbleBtn;
	UILabel		*bubbleLbl;
	NSInteger  		selectedIndex;
	NSTimer		 *timeoutTimer;
	HOLoadingView                       *hintView;
	BOOL		isInited;
}
@property(nonatomic, retain)NSTimer		*bubbleTimer;
@property(nonatomic, retain)HOBaseController                    *controller;
@end

@implementation HOTabViewController
- (void)viewDidLoad
{
	[super viewDidLoad];
	CGRect frame = CGRectMake(0, 0, [HOUtils getScreenWidth], 49);
	UIView *v = [[UIView alloc] initWithFrame:frame];
	UIColor *color = [[UIColor alloc] initWithPatternImage:[HOUtils createImageWithColor:MAIN_BG_COLOR forView:v]];
	v.backgroundColor = color;
	[self.tabBar insertSubview:v atIndex:0];
	self.tabBar.opaque = YES;
	[color release];
	[v release];
	
	hintView = [[HOLoadingView alloc]initForHint];

	
	[[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : MAIN_COLOR_NORMAL}
											 forState:UIControlStateSelected];
	self.controller = [[HOUIMgr sharedInstance] getController:HO_MODULE_TYPE_APP];

	[self setupViewCtrls];
}
- (void)viewWillAppear:(BOOL)animated
{
	self.navigationController.navigationBar.hidden = YES;
	[super viewWillAppear:animated];
	[[[HOUIMgr sharedInstance] getController:HO_MODULE_TYPE_APP] addListener:self];
	
	if(isInited)
		return;
	isInited = YES;
	
	NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
	for(UIViewController *viewCtrl in self.navigationController.viewControllers)
	{
		if(viewCtrl != self)
		{
			[[HOUIMgr sharedInstance] removeObserverFromListener:viewCtrl];
			[viewControllers removeObject:viewCtrl];
		}
	}
	self.navigationController.viewControllers = viewControllers;
	self.tabBar.barTintColor = MAIN_COLOR_NORMAL;  // appTintColor is a UIColor *
	
	if([HOStaticDataMgr sharedInstance].openAppFromPushMessage)
	{
		[HOStaticDataMgr sharedInstance].openAppFromPushMessage  = NO;
		[HOStaticDataMgr sharedInstance].needGotoMyMessage = YES;
		[self setSelectedIndex:3];
	}
	else
	{
		
		if([[[HOStaticDataMgr sharedInstance] getUserInfo] isReportUser])
		{
			[self setSelectedIndex:0];
		}
		else
		{
			[self setSelectedIndex:3];
		}
	}
	
	
	if(isSupportCaiYun)
	{
		[self initCaiyunAccessToken];
	}
//	[self exportSYFContact];
}

- (void)popupHintView:(NSString *)content inTime:(double)time
{
	
//	CGSize size0 = [content sizeWithFont:[UIFont systemFontOfSize:14]];
	
//	CGRect screenBound = [[UIScreen mainScreen] bounds];
//	CGSize screenSize = screenBound.size;
//	CGFloat x = (screenSize.width - size0.width - 20)/2;
	
	//    (screenSize.height - 216 - size0.height)/2 - 64,
	if([hintView superview])
	{
		[hintView removeFromSuperview];
	}
	[self.navigationController.navigationBar addSubview:hintView];
	hintView.layer.borderWidth = [HOUtils defaultOnePixelConversion];
	[hintView show:self.view content:content displayTime:time];


}

#pragma mark
#pragma mark tabbar UIViewController
- (void)setupViewCtrls
{
	HONavigationController *homeNav			 	= [self getNavigationWithIndex:0];
	HONavigationController *msgNav 				= [self getNavigationWithIndex:1];
	HONavigationController *orderNav 			= [self getNavigationWithIndex:2];
	HONavigationController *myNav			    = [self getNavigationWithIndex:3];
	NSArray *controllers = [NSArray arrayWithObjects:homeNav, msgNav, orderNav, myNav, nil];
	self.viewControllers = controllers;
	
}

- (HONavigationController *)getNavigationWithIndex:(NSInteger)index
{
	switch (index) {
		case 0:
		{
			HOReportViewController *viewCtrl = [[[HOReportViewController alloc]init] autorelease];
			viewCtrl.needTabBar = YES;
			viewCtrl.navTitle = NSLocalizedString(@"普通报修", @"普通报修");
			return [self getNavCtrlWithViewCtrl:viewCtrl
									  WithTitle:NSLocalizedString(@"普通报修", @"普通报修")
									 withSelImg:@"tab-putongbaoxiu-lan"
									 withNormal:@"tab-putongbaoxiu-hui"
										withTag:index];
		}
		case 1:
		{
			
			if([[[HOStaticDataMgr sharedInstance] getUserInfo] isReportUser])
			{
				return [self getNavCtrlWithViewCtrl:[[[HOQuickReportViewController alloc]init] autorelease]
										  WithTitle:NSLocalizedString(@"紧急报修", @"紧急报修")
										 withSelImg:@"tab-woyaobaoxiu"
										 withNormal:@"tab-woyaobaoxiu-hui"
											withTag:index];
			}
			else
			{
				return [self getNavCtrlWithViewCtrl:[[[HOReportListViewController alloc]init] autorelease]
										  WithTitle:NSLocalizedString(@"报修列表", @"报修列表")
										 withSelImg:@"tab_baoxiuliubiao"
										 withNormal:@"tab_baoxiuliubiao_hui"
											withTag:index];
			}
			
			
		}
			
			
		case 2:
		{
			if([[[HOStaticDataMgr sharedInstance] getUserInfo] isReportUser])
			{
				return [self getNavCtrlWithViewCtrl:[[[HOReportListViewController alloc]init] autorelease]
										  WithTitle:NSLocalizedString(@"报修列表", @"报修列表")
										 withSelImg:@"tab_baoxiuliubiao"
										 withNormal:@"tab_baoxiuliubiao_hui"
											withTag:index];
			}
			else
			{
				
				return [self getNavCtrlWithViewCtrl:[[[HOAnalyzeViewController alloc]init] autorelease]
										  WithTitle:NSLocalizedString(@"统计", @"统计")
										 withSelImg:@"tab_tongji"
										 withNormal:@"tab_tongji_hui"
											withTag:index];
			}
		}
			case 3:
			return [self getNavCtrlWithViewCtrl:[[[HOMyViewController alloc]init] autorelease]
									  WithTitle:NSLocalizedString(@"我的", @"我的")
									 withSelImg:@"tab_wode"
									 withNormal:@"tab_wode_hui"
										withTag:index];
			
			
 	 default:
			return [[[HONavigationController alloc] init] autorelease];
	}
	return [[[HONavigationController alloc] init] autorelease];
}

- (HONavigationController *)getNavCtrlWithViewCtrl:(UIViewController *)viewCtrl
										 WithTitle:(NSString *)title
										withSelImg:(NSString *)selImg
										withNormal:(NSString *)norImg
										   withTag:(NSInteger)tag
{
	viewCtrl.tabBarItem.title = title;
	viewCtrl.tabBarItem.tag = 1;
	viewCtrl.tabBarItem.selectedImage = [[UIImage imageNamed:selImg]
										 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
	viewCtrl.tabBarItem.image = [[UIImage imageNamed:norImg]
								 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
	HONavigationController *msgNav = [[[HONavigationController alloc]
									   initWithRootViewController:viewCtrl] autorelease];
	return msgNav;
}

- (void)initCaiyunAccessToken
{
//	NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
	NSString *accessToken = nil; //[userData objectForKey:kCY_FIELD_AccessToken];
	[HOGlobalData sharedInstance].caiYunAccessToken = accessToken;
	if(accessToken)
	{
		[self initCaiyunOrgSecret];
	}
	else
	{
		[[self getAppController] requestCaiyunAccessToken];
	}
}

- (void)saveCaiyunAccessToken:(NSString *)accessToken
{
	NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
	[userData setObject:accessToken forKey:kCY_FIELD_AccessToken];
	[userData synchronize];
}

- (void)initCaiyunOrgSecret
{
	LogNor(@"initCaiyunOrgSecret");
	if([[HOGlobalData sharedInstance].caiYunUser isValueValidated])
	{
		LogNor(@"checkoutCaiYunAddressBook");
		[[self getAppController] checkoutCaiYunAddressBook];
	}
	else
	{
		LogNor(@"LoginCaiyun");
		[[self getAppController] LoginCaiyun];
	}
}

- (HOAppController *)getAppController
{
	return (HOAppController *)_controller;
}

- (void)exportSYFContact
{

	NSString *filePath = [[NSBundle mainBundle] pathForResource:@"syfcontact" ofType:@"json"];
	NSData *data = [NSData dataWithContentsOfFile:filePath];
	
	NSError *err = nil;
	id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&err];
	[[self getAppController] exportSYFAB:jsonObject];
}

#pragma mark
- (void)didReceiveResponse:(HOBaseResponseEntity *)response
{
	if(![response isRequestDone])
		return;
	if([response.action isEqualToString:kHO_FIELD_NewMessage])
	{
		unreadImgView.hidden = ![[HOUIMgr sharedInstance] hasUnreadMsg];
	}
	else if([response.action isEqualToString:kCY_ACTION_GetAccessToken])
	{
		LogNor(@"kCY_ACTION_GetAccessToken:%@", response.dataNode);
		NSString *accessToken = [response.dataNode objectForKey:kCY_FIELD_AccessToken];
		[HOGlobalData sharedInstance].caiYunAccessToken = accessToken;
		[self saveCaiyunAccessToken:accessToken];

		[self initCaiyunOrgSecret];
	}
	else if([response.action isEqualToString:kCY_ACTION_Login])
	{
		LogNor(@"kCY_ACTION_Login:%@", response.dataNode);
		[[HOGlobalData sharedInstance].caiYunUser parseDic:response.dataNode];
//		[self.controller requestDepartmentList:0];
		[[self getAppController] checkoutCaiYunAddressBook];
	}
	else if([response.action isEqualToString:kCY_ACTION_ExportContact])
	{
		LogNor(@"kCY_ACTION_ExportContact:%@", response.dataNode);
		if(!response.dataNode)
			return;
		
		/*
		 {
		 deptList =     (
		 {
		 deptId = 1;
		 name = "\U6280\U672f\U90e8";
		 parentId = 0;
		 sequence = 1;
		 },
		 {
		 deptId = 2;
		 name = "\U8fd0\U8425\U90e8";
		 parentId = 0;
		 sequence = 2;
		 }
		 );
		 orgId = 144552;
		 userList =     (
		 {
		 deptId = 0;
		 mobile = 15068866208;
		 name = "\U90ed\U4f1f\U5229";
		 sequence = 1;
		 userId = 10101001193461120;
		 },
		 {
		 deptId = 0;
		 mobile = 18606240858;
		 name = "\U9648\U6d0b\U5578";
		 sequence = 2;
		 userId = 10101001193582888;
		 },
		 {
		 deptId = 1;
		 mobile = 18969039910;
		 name = "\U674e\U5fd7\U660e";
		 sequence = 1;
		 userId = 10101001193411208;
		 }
		 );
		 }
		 */
		
		[[self getAppController] exportSYFAB:response.dataNode];
		
	}
	else if([response.action isEqualToString:kCY_ACTION_GetDepartmentList])
	{
		LogNor(@"kCY_ACTION_GetDepartmentList:%@", response.dataNode);
		NSArray *departments = [response.dataNode objectForKey:kCY_FIELD_Departments];
		for(NSDictionary *dic in departments)
		{
			/*
			 {
			 "deptId": 1,
			 "parentId": 0,
			 "name": "技术部",
			 "order": 1
			 }
			 ]
			 */
			int deptId = [[dic objectForKey:kCY_FIELD_DeptId] intValue];
			HODepartmentEntity *department = [[HOStaticDataMgr sharedInstance] getDepartmentEntityWithId:deptId];

			
			department.departmentId = [[dic objectForKey:kCY_FIELD_DeptId] intValue];
			department.parentId = [[dic objectForKey:kCY_FIELD_ParentId] longValue];
			department.departmentName = [dic objectForKey:kCY_FIELD_Name];
			department.order = [[dic objectForKey:kCY_FIELD_Order] intValue];
			[[self getAppController] requestUserListFromDepartmentId:department.departmentId];
		}
		
	}
	else if([response.action isEqualToString:kCY_ACTION_GetUserListAll])
	{
//		NSLog(@"userAllList:%@", response.dataNode);
	}
	else if([response.action isEqualToString:kHO_ACTION_RegisterUser])
	{
//		NSLog(@"kHO_ACTION_RegisterUser:%@", response.dataNode);
	}
}

- (void)didReceiveCommand:(NSString *)action data:(id)data
{
	if([action isEqualToString:kHO_CMD_MSG_HAS_READ]
	   || [action isEqualToString:kHO_CMD_READ_MESSAGE_FROMDB]
	   || [action isEqualToString:kHO_CMD_READ_NEWMESSAGE_FROMDB]
	   || [action isEqualToString:kHO_CMD_REMOVED_MESSAGE_FROMDB])
	{
		unreadImgView.hidden = ![[HOUIMgr sharedInstance] hasUnreadMsg];
	}
	else if([action isEqualToString:kHO_CMD_ClosePresentViewCtrl])
	{
//		[self setSelectedIndex:selectedIndex];
	}
	else if([action isEqualToString:kHO_CMD_Logout])
	{
		isInited = NO;
		NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
		BOOL existLoginScreenBefore = NO;
		UIViewController *loginViewCtrl = nil;
		for(UIViewController *viewCtrl in viewControllers)
		{
			if([viewCtrl isKindOfClass:[HOLoginViewController class]])
			{
				loginViewCtrl = [viewCtrl retain];
				existLoginScreenBefore = YES;
			}
			
		}
		if(existLoginScreenBefore)
		{
			[self.navigationController popViewControllerAnimated:YES];
			[loginViewCtrl release];
		}
		else
		{
			HOLoginViewController *viewCtrl = [[HOLoginViewController alloc]initWithModule:HO_MODULE_TYPE_USER];
			[viewControllers insertObject:viewCtrl atIndex:0];
			self.navigationController.viewControllers = viewControllers;
			[self.navigationController popViewControllerAnimated:YES];
			[viewCtrl release];
		}
	}
	if([action isEqualToString:kHO_CMD_Token_invalide])
	{
		[self popupHintView:data inTime:3];
	}
	if([action isEqualToString:kHO_CMD_NewMessage])
	{
		int count = [data intValue];
		unreadImgView.hidden = count == 0;
	}
	else if([action isEqualToString:kHO_CMD_ReceiveNotificationMessage])
	{

//		[self setSelectedIndex:3];
		unreadImgView.hidden = ![[HOUIMgr sharedInstance] hasUnreadMsg];
		
//		[self setBubbleContent:NSLocalizedString(@"有新的订单请求", @"有新的订单请求")];
	}
	else if([action isEqualToString:kHO_CMD_UserTypeChange])
	{
		[self setupViewCtrls];
	}
	else if([action isEqualToString:kHO_CMD_gotoMy])
	{
		[self setSelectedIndex:3];
	}
	else if([action isEqualToString:kHO_CMD_OpenMessageFromUrgency])
	{
		[[HOUIMgr sharedInstance].currentViewController.navigationController popToRootViewControllerAnimated:NO];

		[HOStaticDataMgr sharedInstance].needGotoMyMessage = YES;
		if([[HOUIMgr sharedInstance].currentViewController isKindOfClass:[HOMyViewController class]])
		{
			[[HOUIMgr sharedInstance].currentViewController viewWillAppear:YES];
			[[HOUIMgr sharedInstance].currentViewController viewDidAppear:YES];
		}
		else
		{
			[self setSelectedIndex:3];
		}
		
		
		
	}
	else if([action isEqualToString:kHO_CMD_Login])
	{
		[self setupViewCtrls];
	}
	
}

- (void)removeFromSuperViewForSubView:(UIView *)view, ...
{
	va_list args;
	va_start(args, view);
	if (view)
	{
		UIView *otherView;
		while ((otherView = va_arg(args, UIView *)))
		{
			//依次取得所有参数
			if(otherView)
			{
				[otherView removeFromSuperview];
			}
		}
	}
	va_end(args);
}

- (void)dealloc
{
	[HOUtils removeFromSuperViewForViews:translatorImgViewBtn, translatorBtn, bubbleView, bubbleBtn, bubbleLbl];
	[translatorImgViewBtn release];
	[translatorBtn release];
	[bubbleView release];
	[bubbleBtn release];
	[bubbleLbl release];
	self.bubbleTimer = nil;
	[super dealloc];
}

@end

